const router = require('koa-router')();
const snmpUtil = require('../util/snmp')
const ApiError = require('../error/api_error');
const iptableModel = require('../models/iptable')


router.get('/redIpaddrs', async (ctx) => {
  const {ip, port, redKey} = ctx.query;
  var options = {
    port: port,
    retries: 1,
    timeout: 5000,
    backoff: 1.0,
    transport: "udp4",
    trapPort: 162,
    version: snmpUtil.snmp.Version1,
    backwardsGetNexts: true,
    idBitsSize: 32
};
  var session = snmpUtil.snmp.createSession(ip, redKey,options)
  //var oids = ['1.3.6.1.2.1.1.1.0',] //系统信息
  await snmpUtil.getIpaddr(session).then(back=>{
    ctx.body = back
  })

  // session.get(oids, function (error, varbinds) {
  //   if (error) {
  //     if (error.status == 2) console.log("不是叶子结点OID")
  //     else
  //       console.log('eeeeeeeeeeeeee' + error)
  //   } else {
  //     for (var i = 0; i < varbinds.length; i++)
  //       if (snmp.isVarbindError(varbinds[i]))
  //         console.error(snmp.varbindError(varbinds[i]));
  //       else
  //         console.log(varbinds[i].oid + " = " + varbinds[i].value);
  //   }
  //   session.close();
  // })
})
router.get('/redArp', async (ctx) => {
  const {ip, port, redKey} = ctx.query;
  var options = {
    port: port,
    retries: 1,
    timeout: 5000,
    backoff: 1.0,
    transport: "udp4",
    trapPort: 162,
    version: snmpUtil.snmp.Version1,
    backwardsGetNexts: true,
    idBitsSize: 32
};
  var session = snmpUtil.snmp.createSession(ip, redKey,options)
  //var oids = ['1.3.6.1.2.1.1.1.0',] //系统信息
  await snmpUtil.getArp(session).then(back=>{
    ctx.body = back
  })

  // session.get(oids, function (error, varbinds) {
  //   if (error) {
  //     if (error.status == 2) console.log("不是叶子结点OID")
  //     else
  //       console.log('eeeeeeeeeeeeee' + error)
  //   } else {
  //     for (var i = 0; i < varbinds.length; i++)
  //       if (snmp.isVarbindError(varbinds[i]))
  //         console.error(snmp.varbindError(varbinds[i]));
  //       else
  //         console.log(varbinds[i].oid + " = " + varbinds[i].value);
  //   }
  //   session.close();
  // })
})
router.post('/redNetArp', async (ctx) => {
  //const {ip, port, redKey} = ctx.query;
  const {ip, port, redKey} = ctx.request.body.params;
  const {_id:row_id,ips }= ctx.request.body.body
  //console.log(ips)
  var options = {
    port: port,
    retries: 1,
    timeout: 5000,
    backoff: 1.0,
    transport: "udp4",
    trapPort: 162,
    version: snmpUtil.snmp.Version1,
    backwardsGetNexts: true,
    idBitsSize: 32
};
  var session = snmpUtil.snmp.createSession(ip, redKey,options)
  //var oids = ['1.3.6.1.2.1.1.1.0',] //系统信息
  await snmpUtil.getArp(session).then(back =>{
    if(!back.success)  throw new ApiError("snmp-error", back.data);
    //在获取的所有ARP信息表中进行筛选
    var res = back.data.filter(item=>{
      //console.log(item)
      if (ips.some(function (obj,index,array) {
        //如果当前网段的IP行在ARP中有值，则返回arp行数据,是下面返回item，这里只是判断要不要返回
        if(obj.ip == item.ip){ //arp信息写入数据库
          var arpdata = {'mac':item.mac,'time':new Date()}
          //如果查到的MAC和原有记录不一至，说明IP被新MAC占用,把原记录放入oldarp记录去
          if(obj.hasOwnProperty('arp') && obj.arp.mac != item.mac)
            iptableModel.findOneAndUpdate({_id: row_id,'ips._id':obj._id}, { $set:{'ips.$[ip].arp':arpdata,'ips.$[ip].oldarp':obj.arp},}, { arrayFilters:[{'ip._id':obj._id}],new: true, // 返回修改后的数据
    }).exec()
          else //直接写新的arp
            iptableModel.findOneAndUpdate({_id: row_id,'ips._id':obj._id}, { $set:{'ips.$[ip].arp':arpdata},}, { arrayFilters:[{'ip._id':obj._id}],new: true, // 返回修改后的数据
    }).exec()
        }
        return obj.ip == item.ip //条件判断
      }) )

        return item
      // if(ips.find(obj => obj.ip == item.ip) ){
      //   return item
      // }
    })
    ctx.body = res
  })

  // session.get(oids, function (error, varbinds) {
  //   if (error) {
  //     if (error.status == 2) console.log("不是叶子结点OID")
  //     else
  //       console.log('eeeeeeeeeeeeee' + error)
  //   } else {
  //     for (var i = 0; i < varbinds.length; i++)
  //       if (snmp.isVarbindError(varbinds[i]))
  //         console.error(snmp.varbindError(varbinds[i]));
  //       else
  //         console.log(varbinds[i].oid + " = " + varbinds[i].value);
  //   }
  //   session.close();
  // })
})

router.get('/iftable', async (ctx) => {
  const {ip, port, redKey} = ctx.query;
  var options = {
    port: port,
    retries: 1,
    timeout: 5000,
    backoff: 1.0,
    transport: "udp4",
    trapPort: 162,
    version: snmpUtil.snmp.Version1,
    backwardsGetNexts: true,
    idBitsSize: 32
};
  var session = snmpUtil.snmp.createSession(ip, redKey,options)
  //var oids = ['1.3.6.1.2.1.1.1.0',] //系统信息
  await snmpUtil.getIftable(session).then(back=>{
    ctx.body = back
  })

  // session.get(oids, function (error, varbinds) {
  //   if (error) {
  //     if (error.status == 2) console.log("不是叶子结点OID")
  //     else
  //       console.log('eeeeeeeeeeeeee' + error)
  //   } else {
  //     for (var i = 0; i < varbinds.length; i++)
  //       if (snmp.isVarbindError(varbinds[i]))
  //         console.error(snmp.varbindError(varbinds[i]));
  //       else
  //         console.log(varbinds[i].oid + " = " + varbinds[i].value);
  //   }
  //   session.close();
  // })
})

module.exports = router;
